<template>
    <GradientBackground :colors="{
        bg1: '#f8fcf8',                    // 浅绿调白色背景1
        bg2: '#f8fcf8',                    // 浅绿调白色背景2
        color1: '134, 239, 172',           // 浅绿色 (green-300)
        color2: '110, 231, 183',           // 青绿色 (emerald-300)
        color3: '134, 239, 172',           // 重复浅绿色，减少杂色
        color4: '110, 231, 183',           // 重复青绿色，减少杂色
        color5: '187, 247, 208',           // 极浅绿色 (green-200)
        interactive: '134, 239, 172'       // 浅绿色交互
    }">
        <div class="login-container">
            <div class="login-card">
                <div class="login-card-header">
                    <div class="title">
                        <div class="login-title">融禹</div>
                        <div class="login-title" style="font-size: 20px;">智慧能碳管理系统</div>
                    </div>
                    <div class="avatar">
                        <div style="font-size: 20px">用户端登录</div>
                        <div class="account-switcher">
                            <div class="account-avatars-container" ref="avatarsContainer">
                                <div class="account-avatars">
                                    <div v-for="(account, index) in savedAccounts" :key="index"
                                        class="account-avatar-item"
                                        :class="{ 'active': selectedAccountIndex === index }"
                                        @click="selectAccount(account, index)"
                                        :ref="el => { if (el) avatarItems[index] = el }">
                                        <div class="account-avatar-circle" :style="getAvatarCircleStyle(index)">
                                            {{ account.realName ? account.realName.charAt(0) :
                                                account.username.charAt(0) }}
                                        </div>
                                        <!-- 删除按钮 -->
                                        <div class="delete-icon" @click.stop="deleteAccount(index)">
                                            <i class="fa fa-times"></i>
                                        </div>
                                    </div>
                                    <!-- 添加新账号按钮 -->
                                    <div class="account-avatar-item add-new" @click="addNewAccount"
                                        :ref="el => { if (el) avatarItems[savedAccounts.length] = el }">
                                        <div class="account-avatar-circle add"
                                            :style="getAvatarCircleStyle(savedAccounts.length)">
                                            +
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <div class="login-card-body">
                    <form class="login-form" @submit.prevent="handleLogin">
                        <div class="form-item">
                            <div class="form-label">账号</div>
                            <input class="custom-input" v-model="loginForm.username" placeholder="Username" type="text"
                                ref="usernameInput" />
                        </div>
                        <div class="form-item">
                            <div class="password-input-container">
                                <div class="form-label">密码</div>
                                <input class="custom-input password-input" v-model="loginForm.password" type="password"
                                    placeholder="Password" />
                            </div>
                        </div>
                        <div class="form-item">
                            <label class="custom-checkbox" style="position: relative;">
                                <input type="checkbox" v-model="loginForm.rememberMe" />
                                <span class="checkbox-mark">
                                    <i class="fa fa-check checkbox-icon" v-if="loginForm.rememberMe"></i>
                                </span>
                                <span class="checkbox-label">记住我</span>
                            </label>
                        </div>
                        <div class="form-item">
                            <button class="login-button" type="submit" :disabled="loading">
                                <span v-if="!loading">登录
                                    <SvgIcon size="12px" icon="arrowRight"></SvgIcon>
                                </span>
                                <i v-else class="fa fa-spinner fa-spin"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 确认删除对话框 -->
        <div class="confirm-dialog" v-if="showDeleteConfirm">
            <div class="confirm-dialog-content">
                <div class="confirm-title">确认删除</div>
                <div class="confirm-message">确定要删除账号 "{{ accountToDelete ? accountToDelete.username : '' }}" 吗？
                </div>
                <div class="confirm-buttons">
                    <button class="cancel-button" @click="cancelDelete">取消</button>
                    <button class="confirm-button" @click="confirmDelete">确认</button>
                </div>
            </div>
        </div>

        <!-- 引入通知组件 -->
        <NotificationMessage ref="notification" />
    </GradientBackground>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, onBeforeUpdate, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { loginApi } from '@/api/auth';
import { sha256 } from '@/utils/sha256';
import { usePermissionStore } from '@/stores/permission';
import { useUserStore } from '@/stores/userinfo';
import NotificationMessage from '@/components/notification/NotificationMessage.vue';
import GradientBackground from '../../components/background/GradientBackground.vue';
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const notification = ref(null); // 通知组件引用
const selectedAccountIndex = ref(0); // 当前选中的账号索引
const usernameInput = ref(null); // 用户名输入框引用
const userStore = useUserStore(); // 用户存储

// 删除账号相关
const showDeleteConfirm = ref(false);
const accountToDelete = ref(null);
const accountToDeleteIndex = ref(-1);

// 新增：用于滚动头像的 ref
const avatarsContainer = ref(null);
const avatarItems = ref([]);

// 定义本地存储的键名
const SAVED_ACCOUNTS_KEY = 'savedAccounts';

// 从本地存储加载已保存的账号列表
const loadSavedAccounts = () => {
    const savedAccountsStr = localStorage.getItem(SAVED_ACCOUNTS_KEY);
    return savedAccountsStr ? JSON.parse(savedAccountsStr) : [
    ];
};

// 保存账号列表到本地存储
const saveAccountsToStorage = (accounts) => {
    localStorage.setItem(SAVED_ACCOUNTS_KEY, JSON.stringify(accounts));
};

// 模拟已保存的账号列表数据
const savedAccounts = reactive(loadSavedAccounts());

const loginForm = reactive({
    username: '',
    password: '',
    rememberMe: true  // 默认勾选"记住我"
});

// 在每次更新前清空 ref 数组，防止内存泄漏和引用错误
onBeforeUpdate(() => {
    avatarItems.value = [];
});

// 将选中的头像滚动到视图中央
const scrollToSelected = () => {
    // 使用 nextTick 确保 DOM 更新完毕
    nextTick(() => {
        if (selectedAccountIndex.value < 0 || !avatarItems.value[selectedAccountIndex.value]) {
            return;
        }
        const selectedElement = avatarItems.value[selectedAccountIndex.value];
        if (selectedElement && typeof selectedElement.scrollIntoView === 'function') {
            selectedElement.scrollIntoView({
                behavior: 'smooth',
                inline: 'center',
                block: 'nearest'
            });
        }
    });
};

// 监听选中账号索引的变化，自动滚动
watch(selectedAccountIndex, scrollToSelected);

// 监听用户名变化
watch(() => loginForm.username, (newValue) => {
    if (newValue === '') {
        // 当用户名被清空时，选择"添加新账号"头像
        selectedAccountIndex.value = savedAccounts.length;
        loginForm.password = '';
    } else {
        // 当用户名变化但不为空时，检查是否匹配已保存的账号
        const index = savedAccounts.findIndex(account => account.username === newValue);
        if (index !== -1) {
            selectedAccountIndex.value = index;
        }
    }
});


// 获取头像圆圈的样式
const getAvatarCircleStyle = (index) => {
    const isSelected = index === selectedAccountIndex.value;
    const isAddButton = index === savedAccounts.length;

    const style = {
        width: '64px',
        height: '64px',
        fontSize: '24px',
        borderRadius: '22px',
        padding: '10px 16px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        transition: 'all 0.3s ease',
        backgroundColor: 'rgba(255, 255, 255, 1)'
    };

    if (isSelected) {
        style.color = 'rgba(119, 173, 120, 1)';
        style.boxShadow = '0px 8px 24px -8px rgba(40, 89, 223, 0.12)';
    } else {
        style.color = 'rgba(119, 119, 119, 1)';
        style.boxShadow = 'none';
    }

    return style;
};

// 验证表单
const validateForm = () => {
    if (!loginForm.username) {
        notification.value.show('请输入用户名');
        return false;
    }
    if (!loginForm.password) {
        notification.value.show('请输入密码');
        return false;
    }
    if (loginForm.password.length < 6) {
        notification.value.show('密码长度不能少于6位');
        return false;
    }
    return true;
};

// 选择账号
const selectAccount = (account, index) => {
    selectedAccountIndex.value = index;

    // 如果选择已有账号，填写用户名和密码
    if (index < savedAccounts.length) {
        loginForm.username = account.username;
        loginForm.password = account.password; // 设置密码（仅用于演示）
    } else {
        // 如果选择"添加新账号"，清空表单
        loginForm.username = '';
        loginForm.password = '';
    }
};

// 添加新账号
const addNewAccount = () => {
    selectedAccountIndex.value = savedAccounts.length;
    loginForm.username = '';
    loginForm.password = '';
    // 聚焦用户名输入框
    if (usernameInput.value) {
        usernameInput.value.focus();
    }
    // 清空下方的账号显示
    userStore.userinfo = null;
};

// 删除账号
const deleteAccount = (index) => {
    accountToDelete.value = savedAccounts[index];
    accountToDeleteIndex.value = index;
    showDeleteConfirm.value = true;
};

// 取消删除
const cancelDelete = () => {
    showDeleteConfirm.value = false;
    accountToDelete.value = null;
    accountToDeleteIndex.value = -1;
};

// 确认删除
const confirmDelete = () => {
    if (accountToDeleteIndex.value !== -1) {
        // 删除账号
        savedAccounts.splice(accountToDeleteIndex.value, 1);

        // 保存更新后的账号列表
        saveAccountsToStorage(savedAccounts);

        // 如果删除的是当前选中的账号
        if (accountToDeleteIndex.value === selectedAccountIndex.value) {
            if (savedAccounts.length > 0) {
                // 选择第一个账号
                selectedAccountIndex.value = 0;
                loginForm.username = savedAccounts[0].username;
                loginForm.password = savedAccounts[0].password;
            } else {
                // 如果没有账号了，则选择"添加新账号"
                selectedAccountIndex.value = 0;
                loginForm.username = '';
                loginForm.password = '';
            }
        } else if (accountToDeleteIndex.value < selectedAccountIndex.value) {
            // 如果删除的账号在当前选中账号之前，需要更新选中索引
            selectedAccountIndex.value--;
        }

        // 显示删除成功通知
        notification.value.show('账号已删除');
    }

    // 关闭确认对话框
    cancelDelete();
};

// 保存当前账号到已保存列表
const saveCurrentAccount = async () => {
    // 获取用户真实姓名
    const realName = userStore.userinfo?.real_name || loginForm.username;

    const existingIndex = savedAccounts.findIndex(account => account.username === loginForm.username);

    // 如果账号已存在，更新密码和真实姓名
    if (existingIndex !== -1) {
        savedAccounts[existingIndex].password = loginForm.password;
        savedAccounts[existingIndex].realName = realName;
    } else {
        // 否则添加新账号
        savedAccounts.push({
            username: loginForm.username,
            password: loginForm.password,
            realName: realName
        });
    }

    // 保存更新后的账号列表到本地存储
    saveAccountsToStorage(savedAccounts);

    // 更新选中索引为新添加/更新的账号
    selectedAccountIndex.value = existingIndex !== -1 ? existingIndex : savedAccounts.length - 1;
};

// 处理登录
const handleLogin = async () => {
    if (!validateForm()) return;

    try {
        loading.value = true;

        const loginPassword = await sha256(loginForm.password);
        const res = await loginApi(loginForm.username, loginPassword);

        if (res.wechat_bind) {
            userStore.setWechatBind(res.wechat_bind)
        }

        // 设置令牌
        setToken(res);

        // 检查是否为默认密码
        if (loginForm.password === 'Ry@123456') {
            localStorage.setItem('isDefaultPassword', 'true');
        } else {
            localStorage.setItem('isDefaultPassword', 'false');
        }

        // 获取用户信息
        try {
            await userStore.getUserInfo();
            await usePermissionStore().updateUserPermissions();

            // 如果选择了"记住我"，则保存账号到列表（包含真实姓名）
            if (loginForm.rememberMe) {
                await saveCurrentAccount();
            }

            // 登录成功通知
            notification.value.show('登录成功，欢迎回来');
        } catch (error) {
            notification.value.show('登录成功后获取用户信息失败');
        }

        // 跳转到目标页面
        let redirect = route?.query?.redirect || '/';
        router.push(redirect);
    } catch (error) {
        if (error.code === 128) {
            notification.value.show('登录失败，单位已超出使用期限');
        } else {
            notification.value.show(error.message);
        }
    } finally {
        loading.value = false;
    }
};

// 设置令牌
const setToken = (res) => {
    localStorage.setItem('token', res.access_token);
    localStorage.setItem('refresh_token', res.refresh_token);
    if (loginForm.rememberMe) {
        localStorage.setItem('username', loginForm.username);
        localStorage.setItem('rememberMe', 'true');
    } else {
        localStorage.removeItem('username');
        localStorage.removeItem('rememberMe');
    }
};

// 组件挂载时
onMounted(() => {
    const savedUsername = localStorage.getItem('username');
    let permission = localStorage.getItem('permissions');
    if (permission) {
        localStorage.removeItem('permissions');
    }

    if (savedUsername) {
        loginForm.username = savedUsername;
        loginForm.rememberMe = localStorage.getItem('rememberMe') === 'true';

        // 如果保存的用户名与账号列表中的某个用户名匹配，则选中该账号
        const index = savedAccounts.findIndex(account => account.username === savedUsername);
        if (index !== -1) {
            selectedAccountIndex.value = index;
            loginForm.password = savedAccounts[index].password;
        }
    } else if (savedAccounts.length > 0) {
        // 默认选中第一个账号
        selectedAccountIndex.value = 0;
        loginForm.username = savedAccounts[0].username;
        loginForm.password = savedAccounts[0].password;
    }

    // 初始加载时滚动到选中项
    setTimeout(() => {
        scrollToSelected();
    }, 200);
});
</script>

<style scoped>
.page-container {
    position: relative;
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background: url('@/assets/login_bg.png') no-repeat center center;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
}

.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
}

.login-card {
    width: 440px;
    height: 612px;
    padding: 44px;
    display: flex;
    color: rgba(77, 77, 77, 1);
    border-radius: 45px;
    backdrop-filter: blur(80px);
    background-color: rgba(248, 248, 248, 1);
    box-shadow: 0px 8px 24px 0px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    justify-content: center;
    max-width: 100%;
}

.login-card-header {
    width: 100%;
}

.title {
    text-align: center;
    margin-bottom: 39.33px;
    display: flex;
    flex-direction: column;
    gap: 4px
}

.avatar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 29.33px;
    position: relative;
}

.avatar-circle {
    width: 100px;
    height: 100px;
    border-radius: 50px;
    background-color: rgba(255, 255, 255, 0.7);
    box-shadow: 0 16px 16px rgba(0, 0, 0, 0.15);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 40px;
}

.avatar-text {
    margin-top: 10px;
    text-align: center;
    font-size: 16px;
    color: rgba(77, 77, 77, 1);
}

.logo-container {
    margin-bottom: 15px;
    height: 133.18px;
}

.logo-image {
    width: 183.57px;
    height: 133.18px;
}

.login-title {
    text-align: center;
    font-weight: 400;
    font-size: 32px;
    color: rgba(77, 77, 77, 1);
}

.login-card-body {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 15px;
}

.login-form {
    width: 395px;
    max-width: 100%;
}

.form-item {
    margin-bottom: 20px;
}

.form-label {
    margin-bottom: 4px;
}


/* 自定义输入框 */
.custom-input {
    height: 44px;
    width: 100%;
    border-radius: 12px;
    background-color: rgba(255, 255, 255, 1);
    color: rgba(77, 77, 77, 1);
    padding: 10px 16px;
    outline: none;
    border: none;
    font-size: 14px;
    transition: all 0.6s ease;
}

.custom-input:hover {
    box-shadow: 0px 2px 2px -2px rgba(27, 30, 36, 0.1), rgba(111, 143, 114, 0.1), 0px 8px 24px -8px rgba(111, 143, 114, 0.12);
}

.custom-input:focus {
    border: 0.5px solid rgba(119, 173, 120, 1);

}

.custom-input::placeholder {
    color: rgba(77, 77, 77, 1);
    font-size: 14px;
}

.password-input::placeholder {
    letter-spacing: 0px;
}

/* 密码输入框特殊样式 */
.password-input {
    letter-spacing: 3px;
    /* 增加密码字符间距 */
    font-size: 24px;
}

.password-input-container {
    position: relative;
}

/* 修复后的自定义复选框样式 */
.custom-checkbox {
    display: flex;
    align-items: center;
    cursor: pointer;
    user-select: none;
    position: relative;
}

.custom-checkbox input {
    position: absolute;
    left: 0;
    width: 16px;
    height: 16px;
    opacity: 0;
    cursor: pointer;
    z-index: 2;
}

.checkbox-mark {
    position: relative;
    height: 12px;
    /* 改为12px，与input尺寸一致 */
    width: 12px;
    /* 改为12px，与input尺寸一致 */
    background-color: rgba(255, 255, 255, 1);
    border-radius: 8px;
    margin-right: 2.5px;
    /* 增加右边距，更好看 */
    display: flex;
    margin-top: 2px;
    justify-content: center;
    align-items: center;
    z-index: 1;
    /* 添加边框，更清晰 */
    border: 1px solid rgba(200, 200, 200, 0.5);
}

/* 选中状态的样式 */
.custom-checkbox input:checked+.checkbox-mark {
    background-color: rgba(119, 173, 120, 1);
    ;
    border-color: rgba(119, 173, 120, 1);
    ;
}

.checkbox-icon {
    color: white;
    font-size: 8px;
    line-height: 12px;
}

.checkbox-label {
    color: rgba(77, 77, 77, 1);
    font-size: 12px;
    cursor: pointer;
    /* 确保标签也可以点击 */
}

/* 登录按钮 */
.login-button {
    margin-left: auto;
    display: block;
    height: 44px;
    width: 84px;
    border-radius: 12px;
    background-color: rgba(119, 173, 120, 1);
    ;
    color: #fff;
    border: none;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.login-button:hover {
    background-color: rgba(53, 107, 54, 1);
}

.login-button:disabled {
    opacity: 0.7;
    cursor: not-allowed;
}

.account-switcher {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.account-avatars-container {
    width: 100%;
    height: 94px;
    /* 64px高度 + 10px上下padding */
    position: relative;
    overflow: auto;
    /* 隐藏滚动条 */
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE and Edge */
}

.account-avatars-container::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari, and Opera */
}

.account-avatars {
    width: max-content;
    min-width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    align-items: center;
    gap: 10px;
    /* 增加左右内边距，确保第一个和最后一个头像也能居中 */
    padding: 0 150px;
}

.account-avatar-item {
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s ease;
    flex-shrink: 0;
    /* 为删除按钮提供定位上下文 */
    position: relative;
}

.account-avatar-circle {
    transition: all 0.3s ease;
}

.account-avatar-item:hover .account-avatar-circle {
    transform: scale(1.05);
}

/* 删除按钮样式 */
.delete-icon {
    position: absolute;
    top: -5px;
    right: -5px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.9);
    color: rgba(77, 77, 77, 1);
    font-size: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s ease;
    z-index: 20;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
}

.account-avatar-item:hover .delete-icon {
    opacity: 1;
}

.delete-icon:hover {
    background-color: #f44336;
    color: white;
    transform: scale(1.1);
}

/* 确认删除对话框 */
.confirm-dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
}

.confirm-dialog-content {
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 10px;
    padding: 20px;
    width: 300px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.confirm-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    color: rgba(77, 77, 77, 1);
}

.confirm-message {
    margin-bottom: 20px;
    color: rgba(77, 77, 77, 1);
}

.confirm-buttons {
    display: flex;
    justify-content: flex-end;
}

.cancel-button,
.confirm-button {
    padding: 8px 15px;
    margin-left: 10px;
    border-radius: 5px;
    cursor: pointer;
    border: none;
    font-size: 14px;
    transition: all 0.3s ease;
}

.cancel-button {
    background-color: #e0e0e0;
    color: rgba(77, 77, 77, 1);
}

.cancel-button:hover {
    background-color: #d0d0d0;
}

.confirm-button {
    background-color: #f44336;
    color: white;
}

.confirm-button:hover {
    background-color: #e53935;
}

/* 响应式布局 - 移动端适配 */
@media screen and (max-width: 768px) {
    .page-container {
        justify-content: center;
        background-position: left center;
    }

    .login-container {
        width: 100%;
        padding: 5px;
    }

    .login-card {
        width: 100%;
        border-radius: 30px;
    }

    .account-avatars-container {
        overflow-x: auto;
    }

    /* 调整内边距以适应移动端 */
    .account-avatars {
        padding: 0 40vw;
    }

    /* 调整表单宽度 */
    .login-form {
        width: 100%;
        max-width: 320px;
    }

    .custom-input {
        height: 40px;
        font-size: 14px;
    }

    .login-button {
        height: 40px;
        width: 80px;
    }

    .password-input {
        letter-spacing: 0px;
    }
}
</style>